package com.unreal.example.service.impl;

import java.util.List;

import com.unreal.example.bean.AccountInfo;
import com.unreal.example.service.AccountInfoService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class AccountInfoServiceImpl implements AccountInfoService {

    @Autowired
    private MongoTemplate template;

    @Override
    public AccountInfo saveAccountInfo(AccountInfo accountInfo) {
        return template.save(accountInfo);
    }

    @Override
    public List<AccountInfo> listAccountInfo() {
        return template.findAll(AccountInfo.class);
    }

    @Override
    public long updateAccountInfo(AccountInfo accountInfo) {
        Query query = new Query(Criteria.where("account").is(accountInfo.getAccount()));
        Update update = new Update();
        update.set("password",accountInfo.getPassword());
        return template.updateFirst(query, update, AccountInfo.class).getMatchedCount();
    }

    @Override
    public AccountInfo queryAccountInfoByAccount(String account) {
        Query query = new Query(Criteria.where("account").is(account));
        return template.findOne(query,AccountInfo.class);
    }

    @Override
    public AccountInfo removeAccountInfo(AccountInfo accountInfo) {
        Query query = new Query(Criteria.where("account").is(accountInfo.getAccount()).and("password").is(accountInfo.getPassword()));
        return template.findAndRemove(query,AccountInfo.class);
    }

    @Override
    public AccountInfo getAccountInfoById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        return template.findOne(query,AccountInfo.class);
    }
}